package com.sskj.motherboard.handler;

import com.sskj.motherboard.vo.FrameMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CustomProtocolEncoder extends MessageToByteEncoder<FrameMessage> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, FrameMessage frameMessage, ByteBuf byteBuf) throws Exception {
        try {
            byte commandCode = frameMessage.getCommandCode();
            byte commandType = frameMessage.getCommandType();
            byte[] data = frameMessage.getData();

            int dataLength = data != null ? data.length : 0;

            if (dataLength > 65535) {
                log.warn("Data length exceeds the maximum limit of 65535 bytes");
                return;
            }

            byteBuf.writeByte(commandCode);
            byteBuf.writeByte(commandType);
            byteBuf.writeShort(dataLength);

            if (dataLength > 0) {
                byteBuf.writeBytes(data);
            }

            log.info("Sent packet -> CommandCode: 0x{}, CommandType: 0x{}, Length: {}",
                    Integer.toHexString(commandCode & 0xFF),
                    Integer.toHexString(commandType & 0xFF),
                    dataLength);
        } catch (Exception e) {
            log.error("Error encoding packet: ", e);
            throw e;
        }
    }
}
